# -*- coding: utf-8 -*-

from rest_framework.decorators import action
from core.viewset import CustomModelViewSet
from core.response import JsonResponse
from apps.sys.models import Role, User
from apps.sys.user.serializers import UserSerializer
from apps.sys.role.serializers import *
from apps.sys.role.filters import *


class RoleViewSet(CustomModelViewSet):
    """
    角色管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    filterset_class = RoleFilterSet
    create_serializer_class = RoleCreateUpdateSerializer
    update_serializer_class = RoleCreateUpdateSerializer

    @action(detail=True, methods=["GET"])
    def get_menus(self, request, *args, **kwargs):
        """通过角色id获取该角色用于的菜单"""
        queryset = Role.objects.filter(id=kwargs.get("pk"))
        serializer = RoleMenuTreeselectSerializer(queryset, many=True)
        return JsonResponse(data=serializer.data)

    @action(detail=True, methods=["GET"])
    def get_depts(self, request, *args, **kwargs):
        """通过角色id获取该角色用于的部门"""
        queryset = Role.objects.filter(id=kwargs.get("pk"))
        serializer = RoleDeptTreeselectSerializer(queryset, many=True)
        return JsonResponse(data=serializer.data)

    @action(detail=True, methods=["PUT"], permission_classes=[IsAuthenticated])
    def change_status(self, request, *args, **kwargs):
        """修改状态"""
        instance = Role.objects.filter(id=kwargs.get("pk")).first()
        if instance:
            instance.status = request.data["status"]
            instance.save()
            return JsonResponse(data={"status": instance.status}, msg="修改成功")
        else:
            return JsonResponse(msg="修改失败")

    @action(detail=False, methods=["GET"])
    def get_related(self, request, *args, **kwargs):
        """通过角色id获取授权用户列表"""
        role = Role.objects.get(id=request.query_params["roleId"])
        users = role.user_set.filter(is_superuser=False)
        serializer = UserSerializer(users, many=True)
        return JsonResponse(data=serializer.data)

    @action(detail=False, methods=["GET"])
    def get_unrelated(self, request, *args, **kwargs):
        """通过角色id获取未授权用户列表"""
        users = User.objects.exclude(
            roles=request.query_params["roleId"], is_superuser=False
        )
        serializer = UserSerializer(users, many=True)
        return JsonResponse(data=serializer.data)

    @action(detail=False, methods=["PUT"])
    def add_unrelated(self, request, *args, **kwargs):
        """通过角色id为所选用户授权"""
        role = Role.objects.get(id=request.data.get("roleId"))
        role.user_set.add(*request.data.get("userIds"))
        return JsonResponse(msg="添加授权成功")

    @action(detail=False, methods=["PUT"])
    def remove_related(self, request, *args, **kwargs):
        """通过角色id取消所有授权用户"""
        role = Role.objects.get(id=request.data.get("roleId"))
        role.user_set.remove(*request.data.get("userIds"))
        return JsonResponse(msg="取消授权成功")
